<template>
    <div class="change-task-view">

      <div class="top-view">
        <el-form ref="form" :inline="true" :model="datas" class="demo-form-inline" label-width="150px" size="medium" label-position="left" :rules="rules">
          <el-form-item label="任务名称">
            <span>{{datas.task_name}}</span>
          </el-form-item>

          <el-form-item label="项目名称">
            <span>{{projectName}}</span>
          </el-form-item>

          <el-form-item label="计划开始时间" prop="startDate">
              <el-date-picker
                @change="startchange"
                v-model="datas.startDate"
                type="date"
                :editable="false"
                :clearable="false"
                placeholder="请选择开始时间"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="计划结束时间" prop="endDate">
            <el-date-picker
              @change="endchange"
              v-model="datas.endDate"
              type="date"
              :editable="false"
              :clearable="false"
              placeholder="请选择结束时间"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="工期（天）" prop="duration">
            <el-input v-model="datas.duration" @keyup.native="durationProving" @blur="blur"></el-input>
          </el-form-item>

          <el-form-item label="任务负责人">
            <el-select v-model="datas.person_id" @change="personChange">
              <el-option
                v-for="(item,index) in members"
                :key="index"
                :label="item.member_name"
                :value="item.member_id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="任务参与人">
<!--            <el-select-->
<!--              v-model="datas.task_member_id"-->
<!--              @change="memberChange"-->
<!--              multiple-->
<!--              collapse-tags-->
<!--              placeholder="请选择">-->
<!--              <el-option-->
<!--                v-for="item in members"-->
<!--                :key="item.member_id"-->
<!--                :label="item.member_name"-->
<!--                :value="item.member_id">-->
<!--              </el-option>-->
<!--            </el-select>-->

            <template>

              <div v-for="(item,index) in datas.task_member" :key="index">

                <span>{{item.member_name}}</span>

                <el-dropdown v-if="!item.is_add" style="margin-left: 20px" @command="(command)=>{handleCommand(command,index)}">
                  <span class="el-dropdown-link" style="color: #409EFF">
                    更换<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(mem,idx) in getChangeMember()" :key="idx + item.member_id" :disabled="mem.disabled" :command="mem.member_id">{{mem.member_name}}</el-dropdown-item>

                  </el-dropdown-menu>
                </el-dropdown>

                <a v-else style="color: red;margin-left: 20px" @click="deleteMember(index)">删除</a>

              </div>

              <div>

                <el-dropdown placement="bottom-start" @command="(command)=>{handleCommand2(command)}">
                  <span class="el-dropdown-link" style="color: #409EFF">
                    新增
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(mem,idx) in getChangeMember()" :key="idx" :disabled="mem.disabled" :command="mem.member_id">{{mem.member_name}}</el-dropdown-item>

                  </el-dropdown-menu>
                </el-dropdown>

              </div>

            </template>
          </el-form-item>

        </el-form>
      </div>

      <el-form ref="causeForm" :model="datas" class="demo-form-inline" label-width="150px" size="medium" label-position="left" :rules="rules">

        <el-form-item label="变更原因" prop="change_cause_id">
          <el-select v-model="datas.change_cause_id" @change="causeChange">
            <el-option
              v-for="item in causes"
              :key="item.id"
              :label="item.dict_val"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="变更原因描述" prop="work_content">
          <div class="textarea">
            <el-input
              v-model="datas.details_describe"
              type="textarea"
              :rows="2">
            </el-input>
          </div>

        </el-form-item>

        <el-form-item label="变更影响程度" prop="change_level_id">
          <el-select v-model="datas.change_level_id" @change="levelChange">
            <el-option
              v-for="item in changes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="变更影响描述">
          <el-input v-model="datas.change_describe" ></el-input>
        </el-form-item>


      </el-form>

      <el-checkbox v-model="datas.is_update_task_time">自动更新后置任务时间安排</el-checkbox>

    </div>
</template>

<script>
    export default {
        name: "changeTaskView",
        props:{
            projectName:String,
        },
        data:function () {
            return{
                project:{},
                members:[],
                checked:false,
                pickerOptions: {
                    disabledDate:time=> {
                        let bo = false
                        if (time.getTime() < new Date().getTime()){
                            bo = true
                        }
                        if (this.end_time && time.getTime() > new Date(this.end_time.replace(/-/g,'/')).getTime()){
                            bo = true
                        }
                        return bo;

                    }
                },
                datas:{
                    project_id:'',
                    project_name:'',
                    task_id:'',
                    task_name:'',
                    person_id:'',
                    person_in_charge:'',   //申请人
                    duration:0,           //任务工期
                    start_date:'',
                    end_date:'',
                    startDate:'',
                    endDate:'',
                    task_member:[],        //
                    task_member_id:[],
                    change_cause_id:'',    //变更原因
                    change_cause:'',       //变更原因
                    details_describe:'',   //详情描述
                    change_level:'',       //变更影响程度
                    change_level_id:'',    //变更影响程度
                    change_describe:'',    //变更描述
                    is_update_task_time:false,//是否自动更新后置任务时间安排
                    status:3,
                },
                changes:[
                    {
                        value:1,
                        label:'轻微'
                    },
                    {
                        value:2,
                        label:'一般'
                    },
                    {
                        value:3,
                        label:'严重'
                    },
                ],
                causes:[],
                rules: {
                    startDate: [
                        { type: 'date', required: true, message: '请选择开始日期', trigger: 'change' }
                    ],
                    endDate: [
                        { type: 'date', required: true, message: '请选择结束日期', trigger: 'change' }
                    ],
                    duration: [
                        { required: true, message: '请输入工期', trigger: 'blur' }
                    ],
                    change_cause_id: [
                        { required: true, message: '请选择变更原因', trigger: 'change' }
                    ],
                    change_level_id:[
                        { required: true, message: '请选择变更影响程度', trigger: 'change' }
                    ],
                },
                end_time:'',
                duration:0,
            }
        },
        created(){
            this.causes = this.$store.getters.sysDic('task_change')
        },
        methods:{
            validateForm:function(){
                return Promise.all([this.$refs.form.validate(),this.$refs.causeForm.validate()])
            },
            handleCommand2(command){
                let idx = this.members.findIndex(a=>a.member_id == command)
                if (idx != -1){
                    let mem = {...this.members[idx]}
                    mem.is_add = true
                    this.datas.task_member.push(mem)

                }
            },
            handleCommand(command,index) {

                let idx = this.members.findIndex(a=>a.member_id == command)
                if (idx != -1){
                    let mem = {...this.members[idx]}
                    // this.datas.task_member[index] = mem;
                    this.$set(this.datas.task_member,index,mem)

                }
                console.log(this.datas.task_member)
            },
            deleteMember(index){
                this.datas.task_member.splice(index,1)
            },
            getChangeMember:function(){
                let list = []
                for (let i = 0; i < this.members.length; i++){
                    let index = this.datas.task_member.findIndex(a=>a.member_id == this.members[i].member_id)
                    let a = {...this.members[i]}
                    if (index != -1){
                        a.disabled = true;
                    }
                    list.push(a)
                }
                return list

            },
            setData:function(data){

                // this.datas = this.createData();
                this.datas.project_name = this.projectName
                this.datas.project_id = data.project_id
                this.datas.task_id = data.id
                this.datas.person_id = data.person_in_charge.member_id
                this.datas.task_name = data.task_name
                this.datas.person_in_charge = data.person_in_charge
                this.datas.task_member_id = [...data.task_member_id]
                this.datas.task_member = [...data.task_member]
                this.datas.duration = data.duration

                this.datas.start_date = data.start_date
                this.datas.end_date = data.end_date
                this.datas.startDate = new Date(data.start_date.replace(/-/g,'/'))
                this.datas.endDate = new Date(data.end_date.replace(/-/g,'/'))

                this.$api.PROJECT_MANAGER_PROJECT_DETAIL(data.project_id).then(res=>{
                    if (res.code == 200){
                        this.members = res.data.member;
                        this.project = res.data;
                        this.end_time = this.project.plan_end_time

                        if (data.level != 1 && data.parent_id){
                            this.$api.PROJECT_START_TASK_DETAIL(data.parent_id).then(res=>{
                                if (res.code == 200){
                                    this.members = res.data.task_member;
                                    this.end_time = res.data.end_date

                                    this.duration = this.dealDuration(data.start_date,this.end_time) > 1 ? this.dealDuration(data.start_date,this.end_time) - 1 : this.dealDuration(data.start_date,this.end_time)
                                }else{
                                    this.$message.error(res.msg)
                                }
                            }).catch(err=>{

                            })
                        }else{
                            this.duration = this.dealDuration(data.start_date,this.end_time) > 1 ? this.dealDuration(data.start_date,this.end_time) - 1 : this.dealDuration(data.start_date,this.end_time)
                        }
                    }else{
                        this.$message.error(res.msg)
                    }
                }).catch(err=>{

                })



            },
            startchange:function(){
                if (this.datas.startDate){
                    // this.datas.startDate = this.dealDateStr(this.datas.startDate)  + " 00:00:00"
                    this.datas.start_date = this.dealDateStr(this.datas.startDate)  + " 00:00:00"

                    this.duration = this.dealDuration(data.start_date,this.end_time) > 1 ? this.dealDuration(data.start_date,this.end_time) - 1 : this.dealDuration(data.start_date,this.end_time)

                }
                if (this.datas.duration != ""){
                    this.datas.endDate = new Date(this.dealDate(this.datas.startDate,this.datas.duration).replace(/-/g,'/'))
                    this.datas.end_date = this.dealDate(this.datas.startDate,this.datas.duration).replace(/-/g,'/') + " 23:59:59"
                }
            },
            endchange:function(){
                if (this.datas.endDate){
                    // this.datas.endDate = this.dealDateStr(this.datas.endDate)  + " 23:59:59"
                    this.datas.end_date = this.dealDateStr(this.datas.endDate)  + " 23:59:59"

                    this.datas.duration = this.dealDuration(this.datas.startDate,this.datas.endDate)
                    if (!this.datas.duration){
                        this.datas.end_date = ""
                        this.datas.endDate = ''
                    }
                    // let  startDate = Date.parse(this.datas.startDate);
                    // let  endDate = Date.parse(this.datas.endDate);
                    // if (startDate>endDate){
                    //     this.datas.duration = 0;
                    //     this.datas.end_date = ""
                    // }else if (startDate==endDate){
                    //     this.datas.duration = 1
                    // }else{
                    //     let num = ((endDate - startDate)/(1*24*60*60*1000)).toFixed(0)
                    //     let a = Number(num) +  1
                    //     this.datas.duration = a;
                    // }
                    this.$refs.form.validateField("duration")
                }
            },
            dealDuration:function(start,end){
                let a = 0
                let startDate = Date.parse(start);
                let endDate = Date.parse(end);
                if (startDate>endDate){
                    a = 0;
                }else if (startDate==endDate){
                    a = 1
                }else{
                    let num = ((endDate - startDate)/(1*24*60*60*1000)).toFixed(0)
                    a = Number(num) +  1
                }
                return a
            },
            durationProving:function(){
                let str = this.datas.duration
                // this.form.skus[e].Price 是input的值　　
                // 先把非数字的都替换掉，除了数字和.
                str = str.replace(/[^\d]/g, '');

                let num = Number(str)
                if (!num){
                    num = ""
                }else if (num > this.duration) {
                    num = this.duration
                }
                this.datas.duration = num;
            },
            blur:function(){
                if (this.datas.startDate){
                    this.datas.endDate = new Date(this.dealDate(this.datas.startDate,this.datas.duration).replace(/-/g,'/'))
                    this.datas.end_date = this.dealDate(this.datas.startDate,this.datas.duration).replace(/-/g,'/') + " 23:59:59"
                }
                // else if (this.data.endDate != ""){
                //     this.data.startDate = this.dealDate2(this.data.endDate,this.data.days)
                // }
            },
            personChange:function(id){
                let index = this.members.findIndex(a=>a.member_id == id)
                if (index != -1){
                    let data = this.members[index]
                    this.datas.person_in_charge = data
                }

            },
            memberChange:function () {
                this.datas.task_member = [];
                this.datas.task_member_id.forEach(id=>{
                    let index = this.members.findIndex(a=>a.member_id == id)
                    if (index != -1){
                        this.datas.task_member.push(this.members[index])
                    }
                })
            },
            causeChange:function(id){
                let index = this.causes.findIndex(a=>a.id == id)
                if (index != -1){
                    let data = this.causes[index]
                    this.datas.change_cause = data.dict_val;
                }
            },
            levelChange:function(id){
                let index = this.changes.findIndex(a=>a.value == id)
                if (index != -1){
                    let data = this.changes[index]
                    this.datas.change_level = data.label;
                }
            },
            createData:function () {
                let data = {
                    project_id:'',
                    project_name:'',
                    task_id:'',
                    task_name:'',
                    person_id:'',
                    person_in_charge:'',   //申请人
                    duration:0,           //任务工期
                    start_date:'',
                    end_date:'',
                    startDate:'',
                    endDate:'',
                    task_member:[],        //
                    task_member_id:[],
                    change_cause_id:'',    //变更原因
                    change_cause:'',       //变更原因
                    details_describe:'',   //详情描述
                    change_level:'',       //变更影响程度
                    change_level_id:'',    //变更影响程度
                    change_describe:'',    //变更描述
                    is_update_task_time:false,//是否自动更新后置任务时间安排
                    status:3,
                }

                return data;
            },
            dealDate:function(str,days){
                let date = new Date(str.replace(/-/g,'/'));

                if (days){
                    days--
                }

                let timeStr = Number(days) * 24 * 3600;
                if (date.getTime() > 99999999999){
                    timeStr = timeStr * 1000;
                }

                let dd = date.getTime() + timeStr

                let date2 = new Date(dd)

                return this.dealDateStr(date2)
            },
            dealDateStr:function(date){
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                return year + "-" + month + "-" + day
            },
        }
    }
</script>

<style lang="scss">
  @import "@/assets/scss/views/projectManagement/list/details/changeTaskView.scss";
</style>
